package com.carlinfo.stu_ques.common.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.carlinfo.stu_ques.common.dao.IBaseDao;
import com.carlinfo.stu_ques.common.util.FileUtil;
import com.carlinfo.stu_ques.demo.pojo.Dynasty;

public class BaseDaoImpl<T> implements IBaseDao<T>
{
	protected  int id = 1 ;
	protected int tempId;
	protected Map<Integer, T> resultMap = new TreeMap<Integer, T>();
	protected FileUtil fileUtile = new FileUtil();
	protected File parentFile = new File("d:/test");
	protected void readFile(File tarFile)
	{
		try
		{
			FileInputStream fis = new FileInputStream(tarFile);
			Object obj = this.fileUtile.readObject(fis);
			if(obj!=null)
			{
				List<Object> list = new ArrayList<Object>();
				list = (List<Object>) obj;
				this.resultMap = (Map<Integer, T>) list.get(0) ;
				this.id = (int) list.get(1);
			}
		} catch (FileNotFoundException e)
		{

			//System.out.println("文件不存在");
		}

	}
	protected void idCount()
	{
		id ++ ; 
	}
	protected void writeFile(File tarFile)
	{
		List<Object> list = new ArrayList<Object>();
		list.add(resultMap);
		list.add(id);
		try
		{
			if(!tarFile.getParentFile().exists())
			{
				tarFile.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(tarFile);
			if(!this.fileUtile.writeObject(fos,list))
			{
				System.out.println("我存失败了");
			}
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public int saveOneDao(T t)
	{
		this.idCount();
		this.resultMap.put(this.tempId, t);
		return this.tempId;
	}
	@Override
	public void updateOneDao(T t)
	{
		this.resultMap.put(tempId, t);
		
	}
	@Override
	public void deleteOneDao(T t)
	{
		this.resultMap.remove(this.tempId);
		
	}
	@Override
	public List<T> selectListDao()
	{
		List<T> list = new ArrayList<T>();
		/**
		 * 循环Map,打印Map中的内容
		 * 同时将Map中的值对应的List返回
		 */
		Set<Entry<Integer, T>> entrySet = this.resultMap.entrySet() ; 
		for (Iterator iterator = entrySet.iterator(); iterator.hasNext();)
		{
			/* 为啥此处需要强转呢? */
			Entry<Integer, T> entry = (Entry<Integer, T>) iterator.next();
			/* 从entry中取到键和值 */
			int key = entry.getKey() ; 
			T t = entry.getValue() ; 
			//System.out.println(key + "==循环==" + dynasty);
			/* 将朝代放到List中 */
			list.add(t);
		}
		return list;
		
	}
	@Override
	public T selectOneDao(Map<String, Object> condMap)
	{
		if(condMap.get("id")!=null)
		{
			Integer id = (Integer)condMap.get("id");
			return this.resultMap.get(id);
		}
		return null;
	}
}
